<?php
/**
 *劳保局入款
*/
namespace app\admin\controller;
use app\admin\controller\Admin;
use xhadmin\service\admin\record\CustomerService;
use xhadmin\service\admin\MemberService;
use xhadmin\db\Customer as CustomerDb;
use think\facade\Cache;
use think\facade\Db;
use PhpOffice\PhpWord\TemplateProcessor;
use think\facade\App;

class Income extends Admin {


	/*会员管理*/
	function index(){
        if (!$this->request->isAjax()){
			return $this->display('index');
		}else{
            $limit  = $this->request->post('limit', 0, 'intval');
			$offset = $this->request->post('offset', 0, 'intval');
			$page   = floor($offset / $limit) +1 ;

			$id_card= $this->request->param('id_card', '', 'strip_tags,trim');
			$first_name = $this->request->param('first_name', '', 'strip_tags,trim');
			$birth_year = $this->request->param('birth_year', '', 'strip_tags,trim');
			$last_name = $this->request->param('last_name', '', 'strip_tags,trim');
            $id= $this->request->param('id', '', 'strip_tags,trim');

            if(!empty($id)){
                $where['id'] = ['=',$id];
            }
            if(!empty($id_card)){
                $where['id_card'] = ['like','%'.$id_card.'%'];
            }
            if(!empty($birth_year)){
                $where['birth_day'] = ['like','%'.$birth_year.'%'];
            }
            if(!empty($first_name)){
                $where['first_name|last_name|passport_info'] = ['like','%'.$first_name.'%'];
            }
            if(!empty($last_name)){
                $where['last_name'] = ['like','%'.$last_name.'%'];
            }
            $where['status'] = ['=',7];
			$limit = ($page-1) * $limit.','.$limit;
            //p($where);exit;
			try{
				$res = CustomerService::pageListA(formatWhere($where),$limit,'*',$orderby = 'id desc',5);
				foreach ($res['list'] as $key=>&$val) {
				    $val['work_year_month'] = $val['work_year'].'年'.$val['work_month'].'个月';
                    $val['name'] = $val['first_name'].' '.$val['last_name'];
                }
				$list = $res['list'];
			}catch(\Exception $e){
				exit($e->getMessage());
			}

			$data['rows']  = $list;
			$data['total'] = $res['count'];
			return json($data);
		}
	}



	/*修改*/
	function update(){
		if (!$this->request->isPost()){
			$id = $this->request->get('id','','intval');
			if(!$id) $this->error('参数错误');
			$this->view->assign('info',checkData(CustomerDb::getInfo($id)));
			return $this->display('steptwo/info');
		}else{
            $postField = 'id,status,id_card,idcardimg,idcardimgel,bankimg,wjbhzimg,first_name,last_name,birth_day,
			religion,addr,expiry_date,id_card_upside_no,work_year,work_month,mobile,director,is_rename,is_hz_dg,
			is_yhb_dg,is_introducer,introducer';
			$data = $this->request->only(explode(',',$postField),'post');
			try {
                CustomerService::update($data);
			} catch (\Exception $e) {
				$this->error($e->getMessage());
			}
			return json(['status'=>'00','msg'=>'修改成功']);
		}
	}

    /*改为转为劳保局入款*/
    function status() {
        if (!$this->request->isPost()){
            $id = $this->request->get('id','','intval');
            if(!$id) $this->error('参数错误');
            $this->view->assign('info',checkData(CustomerDb::getInfo($id)));
            return $this->display('stepfour/status');
        }else{
            $postField = 'id,status,id_card_lsg_fee,pass_port_lsg_fee';
            $data = $this->request->only(explode(',',$postField),'post');
            try {
                //CustomerService::update($data);

            } catch (\Exception $e) {
                $this->error($e->getMessage());
            }
            return json(['status'=>'00','msg'=>'修改成功']);
        }
    }

	/*删除*/
	function delete(){
		$idx =  $this->request->post('ids', '', 'strip_tags');
		if(!$idx) $this->error('参数错误');
		try{
			$where['id'] = explode(',',$idx);
            CustomerService::delete($where);
		}catch(\Exception $e){
			$this->error($e->getMessage());
		}
		return json(['status'=>'00','msg'=>'操作成功']);
	}

	/*查看数据*/
	function view(){
		$id = $this->request->get('id','','intval');
		if(!$id) $this->error('参数错误');
		try{
			$this->view->assign('info',checkData(CustomerDb::getInfo($id)));
			return $this->display('record/customer/view');
		} catch (\Exception $e){
			$this->error($e->getMessage());
		}
	}



    function getThumbPic(){
        $detail = $this->request->post('detail','','strval');
        preg_match_all('/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg|\.png]))[\'|\"].*?[\/]?>/',$detail,$allImg);
        return json(['status'=>'00','imgurl'=>$allImg[1][0]]);
    }

    public function qingKuan($cid=''){
    	if (!$this->request->isPost() || !empty($cid)){
    		if(empty($cid)){
    			$id= $this->request->param('id', '', 'strip_tags,trim');
    		}else{
    			$id=$cid;
    		}
    		try {
    			$customer=Db::name("customer")->where('id','=',$id)->find();
    			if(!empty($customer)){
    				//业务
    				$director_id=$customer['director_id'];
    				//介绍人
    				$introducer_id=$customer['introducer_id'];
    				//业务信息
    				$director=Db::name('user')->where('user_id','=',$director_id)->field('name')->find();
    				//介绍人信息
    				$introducer=Db::name('introducer')->where('id','=',$introducer_id)->field('name,mobile')->find();
    				$customer['director_name']=!empty($director['name']) ? $director['name'] : '';
    				$customer['introducer_name']=!empty($introducer['name']) ? $introducer['name'] : '';
    				$customer['introducer_mobile']=!empty($introducer['mobile']) ? $introducer['mobile'] : '';
    				$customer['qkd_info']=!empty($customer['qkd_info']) ? json_decode($customer['qkd_info'],true) : [];
    				$customer['idcardimg_one']=!empty($customer['idcardimg']) ? explode('|',$customer['idcardimg'])[0] : '';
                    $customer['qkd_info']['acceptance_no']=!empty($customer['tzsslbh']) ? $customer['tzsslbh'] : '';
    				if(isset($customer['qkd_info']['introducer_mobile'])){
    					$customer['introducer_mobile']=$customer['qkd_info']['introducer_mobile'];
    				}
    				if(isset($customer['qkd_info']['work_year'])){
    					$customer['work_year']=$customer['qkd_info']['work_year'];
    				}

    				if(isset($customer['qkd_info']['work_month'])){
    					$customer['work_month']=$customer['qkd_info']['work_month'];
    				}

                    if(isset($customer['qkd_info']['work_times'])){
                        $customer['work_times']=$customer['qkd_info']['work_times'];
                    }

    				if(isset($customer['qkd_info']['is_rename'])){
    					$customer['is_rename']=$customer['qkd_info']['is_rename'];
    				}

    				if(isset($customer['qkd_info']['dbgx'])){
    					$customer['dbgx']=$customer['qkd_info']['dbgx'];
    				}else{
    					if($customer['is_yhb_dg']==1){
    						$customer['dbgx'][]=1;
    					}
    					if($customer['is_hz_dg']==1){
    						$customer['dbgx'][]=2;
    					}
    					if($customer['is_jlzdg']==1){
    						$customer['dbgx'][]=3;
    					}
    				}
    			}
    			if(!empty($cid)){
    				return $customer;
    			}
    			//p($customer);exit;
		    	$this->view->assign('customer',$customer);
				return $this->display('income/qingKuan');
    		} catch (\Exception $e) {

    		}
    	}else{
    		try {
	    		$id= $this->request->post('id', '', 'strip_tags,trim');
	    		$content= $this->request->post('content', '', 'strip_tags,trim');
	    		// $data=json_encode($content,JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE);
	    		$res=Db::name('customer')->where('id','=',$id)->update(['update_time'=>time(),'qkd_info'=>$content]);
	    		if(empty($res)){
	    			throw new \Exception("保存失败", 1);
	    		}
	    		return json(['status'=>0,'msg'=>'']);
    		} catch (\Exception $e) {
    			return json(['status'=>1,'msg'=>$e->getMessage()]);
    		}
    	}
    }

    //导出请款单
    function export($cid='') {
    	try {
            if(empty($cid)){
                $id = $this->request->request('id','','intval');
            }else{
                $id=$cid;
            }
	        if(empty($id)){
	        	throw new \Exception("缺少参数", 1);
	        }
    	    $customer=$this->qingKuan($id);
    	    if(empty($customer)){
    	    	throw new \Exception("获取信息失败", 1);
    	    }
    		$template = App::getRootPath().'public/template/qkd.docx';
            $phpWordProcessor= new TemplateProcessor($template);
			$phpWordProcessor->setValue('id',$customer['id']);
			$phpWordProcessor->setValue('date',date('Y-m-d'));
			$phpWordProcessor->setValue('create_date',date('Y-m-d',$customer['create_time']));
			if(!empty($customer['idcardimg_one']) && file_exists(App::getRootPath().'public'.$customer['idcardimg_one'])){
				$phpWordProcessor->setImageValue('img',["path" => App::getRootPath().'public'.$customer['idcardimg_one'], "width" =>350, "height" =>450]);
			}else{
				$phpWordProcessor->setValue('img','');
			}
			$phpWordProcessor->setValue('director_name',$customer['director_name']);
			$phpWordProcessor->setValue('mobile',$customer['mobile']);
			$phpWordProcessor->setValue('introducer_name',$customer['introducer_name']);
			$phpWordProcessor->setValue('introducer_mobile',$customer['introducer_mobile']);
			$phpWordProcessor->setValue('work_year',empty($customer['work_year']) ? '_' : $customer['work_year']);
			$phpWordProcessor->setValue('work_month',empty($customer['work_month']) ? '_' : $customer['work_month']);
			$phpWordProcessor->setValue('work_times',empty($customer['work_times']) ? '_' : $customer['work_times']);
			$phpWordProcessor->setValue('is_rename',empty($customer['is_rename']) ? '__' : ($customer['is_rename']==1 ? '是' : '否'));
			$phpWordProcessor->setValue('is_yhb_dg',empty($customer['qkd_info']['dbgx']) ? '___' : (in_array(1, $customer['qkd_info']['dbgx']) ? '√' : '___'));
			$phpWordProcessor->setValue('is_hz_dg',empty($customer['qkd_info']['dbgx']) ? '___' : (in_array(2, $customer['qkd_info']['dbgx']) ? '√' : '___'));
			$phpWordProcessor->setValue('is_jlz_dg',empty($customer['qkd_info']['dbgx']) ? '___' : (in_array(3, $customer['qkd_info']['dbgx']) ? '√' : '___'));
			$phpWordProcessor->setValue('acceptance_no',empty($customer['qkd_info']['acceptance_no']) ? '' : $customer['qkd_info']['acceptance_no']);
			$phpWordProcessor->setValue('zjtp',empty($customer['qkd_info']['zjtp']) ? '否' : ($customer['qkd_info']['zjtp']==1 ? '是' : '否'));
			$phpWordProcessor->setValue('fxzc',empty($customer['qkd_info']['fxzc']) ? '否' : ($customer['qkd_info']['fxzc']==1 ? '是' : '否'));
			$phpWordProcessor->setValue('tgssb',empty($customer['qkd_info']['tgssb']) ? '否' : ($customer['qkd_info']['tgssb']==1 ? '是' : '否'));
			$count=empty($customer['qkd_info']['history']) ? 0 : count($customer['qkd_info']['history']);
			if(empty($count)){
				$phpWordProcessor->setValue('hnzt',' ');
				$phpWordProcessor->setValue('company',' ');
				$phpWordProcessor->setValue('work_addr',' ');
				$phpWordProcessor->setValue('work_content',' ');
			}else{
				$phpWordProcessor->cloneRow('hnzt',$count);
				foreach ($customer['qkd_info']['history'] as $key=>$item) {
					$phpWordProcessor->setValue('hnzt#'.($key+1),$item['hnzt']);
					$phpWordProcessor->setValue('company#'.($key+1),$item['company']);
					$phpWordProcessor->setValue('work_addr#'.($key+1),$item['work_addr']);
					$phpWordProcessor->setValue('work_content#'.($key+1),$item['work_content']);
				}
			}
			$phpWordProcessor->setValue('others',empty($customer['qkd_info']['others']) ? '' : $customer['qkd_info']['others']);
            $outdir = App::getRootPath().'public/download/data/'.date('Ymd',time());
            if(!is_dir($outdir)) {
                mkdir($outdir,'0755',true);
            }
            $file_nm = $customer['id_card'].'.docx';
            $file = $outdir.'/'.$file_nm;
            fopen($file,"w+");
            $phpWordProcessor->saveAs($file);
            //return date('Ymd',time()).'/'.$file_nm;
            if(!empty($cid)){
                return date('Ymd',time()).'/'.$file_nm;
            }
            return json(['status'=>'00','msg'=>'','data'=>['file_nm'=>date('Ymd',time()).'/'.$file_nm]]);

    	} catch (\Exception $e) {
    	    // echo $e->getMessage().$e->getLine();
    		//return false;
            if(!empty($cid)){
                return false;
            }
            return json(['status'=>'500','msg'=>'保存失败'.$e->getLine().$e->getMessage()]);
        }
    }

    //批量导出请款单
    public function batchExport(){
        try {
            $id_list  = $this->request->post('idx','', 'strip_tags,trim');
            $id_arr=explode(',',$id_list);
            if (count($id_arr)>50) {
                throw new \Exception("最多只能同时选择50个", 1);
            }
            $base_path=App::getRootPath().'public/download/data/';
            $base_path=str_replace('\\','/',$base_path);
            $original_name=date('YmdHis').mt_rand(1000,9999).'.zip';
            $file_name=$base_path.$original_name;
            $zip = new \ZipArchive;
            if ($zip->open($file_name,\ZipArchive::CREATE) !== TRUE) {
                throw new \Exception("创建压缩文件失败", 1);
            }
            foreach ($id_arr as $key => $value) {
                $file=$this->export($value);
                // Log::wirte(json_encode($file,JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE));
                if($file){
                    if(file_exists($base_path.$file)){
                        $zip->addFile($base_path.$file,pathinfo($file,PATHINFO_BASENAME));
                    }
                }
            }
            $zip->close();
            if(!file_exists($file_name)){
                throw new \Exception("创建压缩文件失败", 2);
            }
            return json(['status'=>'0','msg'=>['file_path'=>$original_name]]);
        } catch (Exception $e) {
            return json(['status'=>$e->getCode(),'msg'=>$e->getMessage()]);
        }
    }
}

